import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { STColumn, STData, STChange } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'

import { I18NService } from '@core'
import { Terminal, ITerminalQueryParams, ITerminalStatus } from 'app/shared/interfaces/terminal'
import { TerminalService } from '../terminal.abstract.service'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { ESearchType } from '@shared/enums'
import { ISearchSchema } from '@shared/interfaces/search'
import { DataService } from '@shared/services/data.service'
import { StatusTextMapForTerminal } from '@shared/interfaces/common'
import { AAMSFilterInit } from '@shared/interfaces/aams'
import { openDownloadDialog } from 'app/utils/helpers'

@Component({
  selector: 'app-terminals-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class TerminalListComponent extends ListBaseClass<Terminal, ITerminalQueryParams>
  implements OnInit, AAMSFilterInit {
  /* 需要展示的数据 */
  data: Terminal[] = []

  terminalStatusOptions = []

  StatusTextMapForTerminal = StatusTextMapForTerminal

  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplGroup') tplGroup: TemplateRef<void>
  @ViewChild('tplMerchant') tplMerchant: TemplateRef<void>
  @ViewChild('tplStore') tplStore: TemplateRef<void>

  searchSchema: ISearchSchema[] = []
  customSchema: ISearchSchema[] = []

  /* 单元格名称 */
  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    private terminalService: TerminalService,
    private dataService: DataService,
    private modal: NzModalService,
    public aclService: ACLService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit(): void {
    this.initColumns()
    this.generateStatusOptions()
    this.generateSearchSchema()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
    this.initStore()
  }

  onChange(event: STChange): void {
    const { pi, type } = event
    if (type === 'click' || type === 'dblClick') {
      return
    }
    this.params.page = pi
    this.queryTableDataWithParams()
    this.pi = pi
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.terminalService.getList(this.params).subscribe(this.renderList.bind(this))
  }

  viewDetail(record: Terminal) {
    const { termCode, intStoreCode } = record.common
    this.dataService.setTerminal(record as Terminal)
    this.router.navigate([`/biz/terminals/${termCode}/of/${intStoreCode}`])
  }

  // 刷新激活码
  refreshCDKey(record: STData): void {
    const { termCode, intStoreCode } = record.common
    this.terminalService.refreshCdKey(intStoreCode, termCode).subscribe(newCode => {
      this.st.reload()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.REFRESH_SUCCESS'))
    })
  }

  // 展示收款二维码
  showQRCode(record: STData): void {}

  // 导出单条
  export(record: STData): void {
    const { termCode, intStoreCode } = record.common
    let params: ITerminalQueryParams = {
      page: this.params.page,
      size: this.params.size,
    }
    Object.assign(params, this.params)
    params = {
      ...params,
      termCode,
      intStoreCode,
    }
    this.goExport(params)
  }

  // 编辑
  edit(record: STData): void {}

  query(event: any): void {
    Object.assign(this.params, event)
    this.queryTableDataWithParams()
  }

  handleAction(): void {
    alert('action 按钮被按啦')
  }

  goNew(): void {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  /** 导出列表 */
  exportAll(): void {
    this.goExport(this.params)
  }

  /** 冻结对话框 */
  freezeDialog(record: Terminal): void {
    const { termCode } = record.common
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.TERMINAL_FREEZE_CONFIRM', { termCode }),
      nzOnOk: () => this.freeze(record),
    })
  }

  /** 解冻对话框 */
  unfreezeDialog(record: Terminal): void {
    const { termCode } = record.common
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.TERMINAL_UNFREEZE_CONFIRM', { termCode }),
      nzOnOk: () => this.unfreeze(record),
    })
  }

  /** 冻结操作 */
  freeze(record: Terminal): void {
    const { intStoreCode, termCode } = record.common
    this.terminalService.freeze(intStoreCode, termCode).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  /** 解冻操作 */
  unfreeze(record: Terminal): void {
    const { intStoreCode, termCode } = record.common
    this.terminalService.unfreeze(intStoreCode, termCode).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  private goExport(params: ITerminalQueryParams) {
    this.terminalService.getTerminalReport(params).subscribe(data => {
      const { url } = data
      openDownloadDialog(url, '导出终端')
    })
  }

  private generateStatusOptions(): void {
    for (const item in ITerminalStatus) {
      const option = { label: this.trans(StatusTextMapForTerminal[ITerminalStatus[item]]), value: ITerminalStatus[item] }
      this.terminalStatusOptions.push(option)
    }
  }

  private generateSearchSchema(): void {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createTime',
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.TERMINAL.CODE',
        labelI18n: 'GENERAL.TERMINAL.CODE',
        index: 'termCode',
        type: ESearchType.input,
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        options: this.terminalStatusOptions,
        type: ESearchType.selection,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.tplGroup,
        customFunc: () => this.selectedGroup && this.selectedGroup.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.tplMerchant,
        customFunc: () => this.selectedMerchant && this.selectedMerchant.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.STORE',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.tplStore,
        customFunc: () => this.selectedStore && this.selectedStore.code,
      },
    ]
  }

  private initColumns(): void {
    const canLock = this.aclService.canAbility('api.put.camel.terminal.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.terminal.one.unfreeze')
    const canDownload = this.aclService.canAbility('api.get.camel.terminals.report')
    const canRefreshCDKey = this.aclService.canAbility('api.put.camel.terminal.one.cdkey')
    this.columns = [
      {
        type: 'link',
        title: '终端编号',
        i18n: 'GENERAL.TERMINAL.CODE',
        index: 'common.termCode',
        fixed: 'left',
        width: '120px',
        className: 'text-center',
        click: this.viewDetail.bind(this),
      },
      {
        title: '门店名称',
        i18n: 'GENERAL.STORE.NAME',
        index: 'common.storeName',
        width: '150px',
        className: 'text-left',
      },
      {
        title: '状态',
        i18n: 'GENERAL.INFO.STATUS',
        index: 'common.status',
        width: '120px',
        className: 'text-center',
        render: 'status',
      },
      {
        title: '激活码',
        i18n: 'BIZ.TERMINAL.REDEEM_CODE',
        width: '150px',
        className: 'text-left',
        render: 'cdKey',
      },
      {
        title: '备注',
        i18n: 'GENERAL.INFO.REMARK',
        index: 'common.remark',
        width: '300px',
        className: 'text-left',
      },
      {
        title: '创建时间',
        i18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createdAt',
        type: 'date',
        width: '300px',
      },
      {
        title: '操作',
        i18n: 'GENERAL.INFO.OPERATION',
        width: '200px',
        fixed: 'right',
        className: 'text-center p-xs',
        iif: () => canLock || canUnlock || canDownload || canRefreshCDKey,
        buttons: [
          {
            text: '',
            click: this.refreshCDKey.bind(this),
            icon: {
              iconfont: 'icon-refresh-twotone',
              type: 'iconfont',
            },
            iif: () => canRefreshCDKey,
          },
          {
            text: '',
            click: this.export.bind(this),
            icon: {
              iconfont: 'icon-download-twotone',
              type: 'iconfont',
            },
            iif: () => canDownload,
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            // 未激活状态可以冻结，解冻后转变为正常状态
            iif: record => canLock && (record.common.status === 'normal' || record.common.status === 'init'),
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeDialog.bind(this),
            iif: record => canUnlock && record.common.status === 'freeze',
          },
        ],
      },
    ]
  }
}
